<template>
  <rx-layout>
    <div slot="left" width="200" showButton="true">
      <rx-fit>
        <rx-category-treeeditor
          cat-key="BPM"
          :statisticConfig="statisticConfig"
          read-key="task.read"
          :edit="false"
          @handSelect="handSelect"
          v-if="isShowManageTree"
          :isAdmin="isManageToTree"
          :treeRootList="treeRootList"
          :isBpmClient="isMyBpmClient"
          :isMyBpm="isMyBpmClient"
          :async="true"
        ></rx-category-treeeditor>
      </rx-fit>
    </div>
    <div slot="center">
      <rx-fit :isheader="isheader">
        <div slot="toolheader" foldheader="true" foldbtn="false" border="false">
          <div class="table-operator">
            <a-button type="primary" @click="handBatApprove"  ><a-icon type="check-square" />{{i18n('list.batchApply','批量审批')}}</a-button>
          </div>
          <span class="search-btn-box" v-if="!isheader">
            <span class="search-btn" @click.stop="searchshow"><i class="iconfont iconguolv"></i>{{$ti18('rxList.leachBtn','过滤')}}</span>
          </span>
        </div>
        <div btnalign="right"  slot="searchbar" v-if="fitSearch" @search="search" @cancel="cancel" @close="closeSearchbar">
          <a-form :layout="colLayout">
            <a-row :gutter="24">
              <a-col :span="colSpan">
                <a-form-item :label="i18n('form.itemTitle','事项标题')">
                  <a-input :placeholder="i18n('form.itemTitle','事项标题','input')" v-model="queryParam['Q_v.SUBJECT__S_LK']" />
                </a-form-item>
              </a-col>
              <a-col :span="colSpan">
                <a-form-item :label="i18n('form.billNo','单号')">
                    <a-input :placeholder="i18n('form.billNo','单号','input')" v-model="queryParam['Q_v.BILL_NO__S_LK']" />
                </a-form-item>
              </a-col>
              <a-col :span="colSpan">
                  <a-form-item :label="i18n('form.node','审批环节')">
                    <a-input :placeholder="i18n('form.node','审批环节','input')" v-model="queryParam['Q_v.NAME__S_LK']" />
                  </a-form-item>
              </a-col>
              <a-col :span="colSpan" v-if="isheader">
                    <span class="table-page-search-submitButtons">
                        <a-button type="primary"  icon="search" @click="search">{{$ti18('rxList.searchBtn','查询')}}</a-button>
                        <a-button style="margin-left: 4px"  @click="cancel">{{$ti18('rxList.resetBtn','重置')}}</a-button>
                        <a @click="toggleAdvanced" style="margin-left: 8px">
                          {{ advanced ? i18n('list.putAwayBtn','收起') : i18n('list.expansionBtn','展开') }}
                          <a-icon :type="advanced ? 'up' : 'down'" />
                        </a>
                    </span>
              </a-col>
              <template v-if="advanced">
                  <a-col :span="colSpan">
                <a-form-item :label="i18n('list.taskCreateTime','创建时间') + i18n('list.from','从')">
                  <a-date-picker
                    style="width: 100%"
                    :placeholder="i18n('list.taskCreateTime','请输入任务创建时间','input')"
                    v-model="queryParam['Q_v.CREATE_TIME__D_GE']"
                    format="YYYY-MM-DD"
                    @change="searchRangeDateChange($event,$event,{queryField:'Q_v.CREATE_TIME__D_GE'},'YYYY-MM-DD')"
                  />
                </a-form-item>
                  </a-col>
                  <a-col :span="colSpan">
                <a-form-item :label="i18n('list.to','至')">
                  <a-date-picker
                    style="width: 100%"
                    :placeholder="i18n('list.taskCreateTime','请输入任务创建时间','input')"
                    v-model="queryParam['Q_v.CREATE_TIME__D_LE']"
                    format="YYYY-MM-DD"
                    @change="searchRangeDateChange($event,$event,{queryField:'Q_v.CREATE_TIME__D_LE'},'YYYY-MM-DD')"
                  />
                </a-form-item>
                  </a-col>
              </template>
            </a-row>
          </a-form>
        </div>
        <rx-grid
          ref="table"
          v-if="isShowManageTree"
          :bordered="isBorder"
          :allowRowSelect="true"
          :multiSelect="true"
          :columns="columns"
          :defaultPageSize="10"
          url="/api-bpm/bpm/core/bpmTask/myTasks"
          :queryParam="queryParam"
          data-field="result.data"
          :pageSizeOptions="['10', '30', '40']"
          id-field="taskId"
          :loadDataOnstart="true"
          @selectChange="onSelectChange"
          @getListData="loadDataAgen"
        >
          <span slot="appId" slot-scope="{ text, record }">
              {{allApps[text]?$i18(allApps[text].appName,'应用名称'):$ti18('rxList.noAppName','无')}}
          </span>
          <span slot="billNo" slot-scope="{ text, record, index }">
                {{ record.billNo }}
          </span>
          <span slot="status" slot-scope="{ text, record, index }">
            <a-tag v-if="record.status == 'UNHANDLE'" color="red">{{i18n('form.wait','待办')}}</a-tag>
            <a-tag v-else-if="record.status == 'HANDLE'" color="green">{{i18n('form.processing','处理中')}}</a-tag>
          </span>
          <span slot="assignee" slot-scope="{ text, record }">
            <span>
              <a-tag v-for="taskExe in record.taskExecutors"
                ><a-icon :type="taskExe.type"></a-icon>&nbsp;{{ taskExe.name }}</a-tag
              >
            </span>
          </span>
          <span slot="batchTaskType" slot-scope="{ text, record }">
            <a-tag :color="batchTaskTypeMap[text].color">
            <span>{{ batchTaskTypeMap[text].text }}</span>
            </a-tag>
          </span>
          <span slot="action" slot-scope="{ text, record }">
             <a @click.stop="handleTask(record)">{{i18n('list.handle','办理')}}</a>
          </span>
        </rx-grid>
      </rx-fit>
    </div>
  </rx-layout>
</template>


<script>
import { AppBaseList, RxLayout, Util, RxFit, RxGrid } from '@lowcode/jpaas-common-lib'
import RxCategoryTreeeditor from '@/components/redxun/rx-category-treeeditor'
import TaskBatApprove from "./TaskBatApprove";
import TaskBatchApprove from "./TaskBatchApprove";
import FlowUtil from "../js/FlowUtil";
import { mapState} from 'vuex';
import AppSearch from "@/views/modules/share/AppSearch";
import RxSearchApp from "@/views/modules/share/rx-search-app";
import instAndTaskShare from "@/views/modules/bpm/core/js/instAndTaskShare";

export default {
  name: 'BpmTaskList',
  mixins: [AppBaseList,instAndTaskShare,FlowUtil,AppSearch],
  components: {
    RxLayout,
    RxFit,
    RxGrid,
    RxCategoryTreeeditor,
    TaskBatApprove,
    RxSearchApp
  },
    computed: {
        ...mapState({
            // 所属应用
            allApps: state => state.appSetting ? state.appSetting.allApps : {}
        }),
    },
  data() {
    return {
      treeData: [],
      selTreeId: '',
      gridData: [],

      // 查询参数
      queryParam: {},

      // 表头
      columns: [
        {
          title: this.$ti18('rxList.index','序号'),
          type: 'indexColumn',
          dataIndex: 'serial',
          scopedSlots: { customRender: 'serial' },
          width: 60,
        },
        {
          title: this.i18n('form.itemTitle','事项标题'),
          dataIndex: 'subject',
          width: 180,
          ellipsis: false,
        },
        {
          title: this.i18n('form.billNo','单号'),
          dataIndex: 'billNo',
          width: 180,
          scopedSlots: { customRender: 'billNo' },
        },
        {
          title: this.i18n('form.node','审批环节'),
          dataIndex: 'name',
          width: 100,
        },
        {
          title: this.i18n('form.status','状态'),
          dataIndex: 'status',
          scopedSlots: { customRender: 'status' },
          width: 120,
        },
          {
              title: this.i18n('form.taskType','任务类型'),
              dataIndex: 'batchTaskType',
              scopedSlots: { customRender: 'batchTaskType' },
              width: 80,
          },
      {
          title: this.i18n('form.appId','所属应用'),
          dataIndex: 'appId',
          width: 100,
          sortField: 'APP_ID_',
          scopedSlots: {customRender: 'appId'}
      },
        {
          title: this.i18n('form.sendTime','发送时间'),
          dataIndex: 'createTime',
          width: 120,
        },
        {
          title: this.$ti18('rxList.action','操作'),
          dataIndex: 'action',
          width: 60,
          scopedSlots: { customRender: 'action' },
        },
      ],

      selectedRowKeys: [],
      selectedRows: [],
      statisticConfig: {
        type:"static_bpm",
        appIdPrefix:'t.',
        table:"(SELECT t.* FROM BPM_TASK t " +
                "WHERE ASSIGNEE_ = #{w.curUserId,jdbcType=VARCHAR} AND t.TENANT_ID_ = #{w.curTenantId,jdbcType=VARCHAR} AND t.STATUS_ != 'COMPLETED' " +
                "AND t.STATUS_ != 'LOCKED' AND t.STATUS_ != 'PENDING' AND (t.BATCH_TASK_TYPE_ != 'BATCH_SUB' or t.BATCH_TASK_TYPE_ IS NULL ) UNION SELECT t.* " +
                "FROM BPM_TASK t  " +
                "LEFT JOIN BPM_TASK_USER u ON t.TASK_ID_ = u.TASK_ID_ " +
                "WHERE t.ASSIGNEE_ IS NULL AND t.STATUS_ != 'COMPLETED' AND t.STATUS_ != 'LOCKED' AND t.STATUS_ != 'PENDING' " +
                "AND (u.USER_ID_ = #{w.curUserId,jdbcType=VARCHAR} AND t.TENANT_ID_ = #{w.curTenantId,jdbcType=VARCHAR} OR u.GROUP_ID_ IN (${w.curUserRoles}))) t",
        tableParams:[{name:"curUserId", type:"string", value:"curUserId", valueType:"context"},
                     {name:"curTenantId", type:"string", value:"curTenantId", valueType:"context"},
                     {name:"curUserRoles", type:"string", value:"curUserRoles", valueType:"context"},
                    ],
        field:"t.TREE_ID_",
        whereConf:[]
      },
      isMyBpmClient:true,
      readKey:"task.read",
      readType:"task",
      isInit:true,
      treePrefix:'v.',
        batchTaskTypeMap: {
            "BATCH_PARENT": {color: 'red', text: this.i18n('taskApply.mergeTasks','任务合并')},
            "": {color: 'green', text: this.i18n('taskApply.publicTasks','普通任务')}
        },
        broadCastChannel:{}
    }
  },
  filters: {},
  beforeDestroy() {
      this.broadCastChannel.close();
  },
  created() {
      this.onLoadTree && this.onLoadTree.call(this)
      this.initBroadCastChannel();
  },
  methods: {
    i18n(name,text,key){
        return this.$ti18(name,text,"MyBpmTask",key);
    },
    initBroadCastChannel(){
      let self_=this;
      this.broadCastChannel = new BroadcastChannel("broadCastChannel");
      //当待办审批完成关闭时，进行待办列表刷新
      this.broadCastChannel.onmessage=function (event){
          if(event.data && event.data.type=='refreshTask'){
              self_.search();
          }
      }
    },
    searchRangeDateChange(date,dateString,e,format){
      if(date.length==2){
          this.queryParam[e.queryField]=date[0].format('YYYY-MM-DD');
      }else {
          this.queryParam[e.queryField]=date.format(format);
      }
    },
    handSelect(curRow) {
        this.loadDataBySelectTreeNode(curRow);
    },
    toggleAdvanced() {
      this.advanced = !this.advanced
    },
    onSelectChange(selectedRowKeys, selectedRows) {
      this.selectedRowKeys = selectedRowKeys
      this.selectedRows = selectedRows
    },
    handleTask(record) {
        if("BATCH_PARENT" === record.batchTaskType){
            let self_ = this;
            Util.open(
                {
                    component: TaskBatchApprove,
                    curVm: this,
                    max:true,
                    title:  this.i18n('taskApply.mergeBatchTasks','任务合并批量审批'),
                    data: {
                        bpmTask: record
                    }
                },
                function (action) {
                    self_.refreshGrid();
                }
            )
            return;
        }
      this.openInst(record.appId,record.instId,record.taskId);
    },
      isContaionBatchTask(rows){
          let task = rows.find(item => {
              return "BATCH_PARENT" === item.batchTaskType;
          });
          return task;
      },
    handBatApprove(){
        var rows=this.$refs.table.getSelectedRows();
        if(!rows || rows.length==0){
            this.$notification.warning({
                message: this.$ti18('rxMsa.tipsInfo','提示信息'),
                description:
                    this.i18n('msa.batchSelectTips','请选择需要审批的任务!'),
            });
            return;
        }
        if(task && task.taskId){
            this.$notification.warning({
                message: this.$ti18('rxMsa.tipsInfo','提示信息'),
                description:this.i18n('msa.batchTips_1','单号【')+task.billNo+this.i18n('msa.batchTips_2','】为合并审批任务，不能进行批量审批!'),
            });
            return;
        }
        var taskAry=rows.map(item=>{
            return item.taskId;
        });
        let self_ = this;
        Util.open(
            {
                component: TaskBatApprove,
                curVm: this,
                // widthHeight:['1000px','600px'],
                max:true,
                title:  this.i18n('taskApply.pageTitle','任务批量审批'),
                data: {
                    taskIds: taskAry.join(",")
                },
                cancel:function (){
                    self_.refreshGrid();
                }

            },
            function (action) {
                self_.refreshGrid();
            }
        )
    },
    toggleSearch() {
      this.showSearch = !this.showSearch
    },
     search() {
      this.$refs.table.loadData()
    },
    closeSearchbar(){
      //关闭过滤弹窗；（点击X触发）
      this.fitSearch = false ;
    }
  },
}
</script>
<style scoped>

</style>

